package info.techgeek.labs.collection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;

public class ConcurrencyThreadsTest extends Thread {
    char c;
    Map<String, String> map ;
    
    ConcurrencyThreadsTest(char c ,Map<String, String> map) {
        this.c = c;
        this.map = map;
    }        
    
//    public void run() {
//        for(int i=0; i<100; i++) {
//            System.out.print(c);
//        }
//    }

    public void run() {
    	
            System.out.println(c+" Map Size Before "+map.size());
            //clearMapIterator(map,c);
            //clearMapGenerics1(map);
            clearMapGenerics(map);
            
            System.out.println(c+" Map Size After "+map.size());
            
            /*
            synchronized (map) {
			}
			*/
    }    

    public void clearMapIterator(Map<String, String> map,char c){
		Set<String> keySet = map.keySet();
		synchronized (keySet) {
			System.out.println("Inside Synchronized "+c);
            for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
            	map.remove(it.next());
            }
        }
	}
	public void clearMapGenerics(Map<String, String> map){
		Set<String> keySet = map.keySet();
		for(String key : keySet){
			map.remove(key);
		}
	}
	public void clearMapGenerics1(Map<String, String> map){
		Set<String> keySet = map.keySet();
		List<String> keyList = new ArrayList<String>();
		
		for(String key : keySet){
			keyList.add(key);
		}
		for(String key : keyList){
			map.remove(key);
		}
	}
    
    public static void main(String[] args) {
    	
    	Map<String, String> map = new WeakHashMap<String, String>();
		map.put("1", "one");
		map.put("2", "two");
		map.put("3", "three");
		map.put("4", "four");
		map.put("5", "five");
		map.put("6", "six");
		
    	ConcurrencyThreadsTest bt1 = new ConcurrencyThreadsTest('1',map);
    	ConcurrencyThreadsTest bt2 = new ConcurrencyThreadsTest('2',map);
    	ConcurrencyThreadsTest bt3 = new ConcurrencyThreadsTest('3',map);
    	ConcurrencyThreadsTest bt4 = new ConcurrencyThreadsTest('4',map);
    	ConcurrencyThreadsTest bt5 = new ConcurrencyThreadsTest('5',map);

	    // start RunBasicThread objects as threads
	    new Thread(bt1).start();
//	    new Thread(bt2).start();
//	    new Thread(bt3).start();
//	    new Thread(bt4).start();
//	    new Thread(bt5).start();
	}
}

